package com.kelvin.paopao.module.qrcode.scan;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.SurfaceView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.google.zxing.client.android.AutoScannerView;
import com.google.zxing.client.android.BaseCaptureActivity;
import com.google.zxing.client.android.Intents;
import com.kelvin.kelvinlib.utils.CommonUtil;
import com.kelvin.paopao.R;
import com.kelvin.paopao.module.qrcode.webview.ScanWebViewActivity;
import com.kelvin.paopao.widgets.CustomToolbar;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/6/19.
 */

public class ScanActivity extends BaseCaptureActivity {
    @BindView(R.id.custom_toolbar)
    CustomToolbar customToolbar;
    @BindView(R.id.preview_view)
    SurfaceView previewView;
    @BindView(R.id.autoscanner_view)
    AutoScannerView autoscannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        ButterKnife.bind(this);
        customToolbar.showBackIcon(this);

        getPermission();
    }

    /**
     * 获取权限
     */
    private void getPermission() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            //全部同意
                            if (isResume) {
                                initCamera(previewView.getHolder());
                                autoscannerView.setCameraManager(cameraManager);
                            }
                        } else {
                            finish();
                        }
                    }
                });
    }

    private boolean isResume;

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        autoscannerView.setCameraManager(cameraManager);
    }

    @Override
    public SurfaceView getSurfaceView() {
        return previewView;
    }

    @Override
    public void dealDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        playBeepSoundAndVibrate(true, false);
        if (CommonUtil.isUrlImage(rawResult.getText())) {
            ScanWebViewActivity.launch(this, rawResult.getText().trim());
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, ScanActivity.class);
        context.startActivity(intent);
    }

}
